package com.qywx.task;


import com.alibaba.fastjson.JSONObject;
import com.qywx.dao.DepartmentDao;
import com.qywx.dao.TagDao;
import com.qywx.dao.UserDao;
import com.qywx.entity.DepartmentEntity;
import com.qywx.entity.TagEntity;
import com.qywx.entity.UserEntity;
import com.qywx.entity.UserTagEntity;
import com.qywx.service.impl.DepartmentServiceImpl;
import com.qywx.service.impl.UserServiceImpl;
import com.qywx.utils.RestTemplateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Component
@EnableScheduling
public class ScheduleInvite {
    @Autowired
    UserDao userDao;
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private TagDao tagDao;
    private final static Logger log = LoggerFactory.getLogger(DepartmentServiceImpl.class);

    //定时邀请每三天凌晨邀请一次
    //@Scheduled(cron = "0 0 0 */3 * ?")
    public void scheduled() {
        //获取所有status状态不为1的
        List<String> idList = userDao.findAllUser();
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("user", idList);
        //设置请求头https://qyapi.weixin.qq.com/cgi-bin/user/get
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        //请求体
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
        String accessToken = restTemplateUtil.getaccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/invite?access_token=" + accessToken;
        //发起请求
        Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
        log.info("执行事件" + new Date());
    }


    //每个小时运行一次
    //@Scheduled(cron = "0 0 * * * ?")
    public void getStatus() {
        //获取所有status状态不为1的
        List<String> idList = userDao.findAllUser();
        String accessToken = restTemplateUtil.getaccessToken();
        if (idList.size() > 0) {
            for (int i = 0; i < idList.size(); i++) {
                String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken + "&userid=" + idList.get(i);
                Map resultMap = restTemplate.getForObject(getUrl, Map.class);
                Integer code = (Integer) resultMap.get("errcode");
                if (0 == code) {
                    int status = (int) resultMap.get("status");//激活状态: 1=已激活，2=已禁用，4=未激活
                    if (1 == status) {
                        userDao.updateStatus(idList.get(i));
                    }
                }
            }
        }
        log.info("执行事件" + new Date());
    }

    /**
     * 人员比较同步
     * 每日凌晨五十分执行
     */
    //@Scheduled(cron = "0 50 0 1/1 * ?")
    //@Scheduled(cron = "0 9/10 * * * ?")
    public void userComparison() {
        String accessToken = restTemplateUtil.getaccessToken();
        //获取部门列表
        String deptUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + accessToken;
        Map resultMapDep = restTemplate.getForObject(deptUrl, Map.class);
        log.info(resultMapDep.toString());
        //获取所有部门
        List departmentList = (List) resultMapDep.get("department");
        for (int a = 0; a < departmentList.size(); a++) {
            Map departmentMap = (Map) departmentList.get(a);
            Integer id = (Integer) departmentMap.get("id");
            //部门人员信息
            String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + accessToken + "&department_id=" + id + "&fetch_child=" + 0;
            Map resultMap = restTemplate.getForObject(getUrl, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            if (code == 0) {
                List userList = (List) resultMap.get("userlist");
                log.info("=========人员数量======" + userList.size());
                //循环企业微信人员与平台作比较
                for (int i = 0; i < userList.size(); i++) {
                    Map map = (Map) userList.get(i);
                    String userid = map.get("userid").toString();
                    //根据userid获取成员信息
                    UserEntity userEntity = userDao.selectDetailById(userid);
                    if (userEntity == null) {
                        //查询不到新增
                        UserEntity user = new UserEntity();
                        user.setUserid(map.get("userid").toString());
                        user.setName(map.get("name").toString());
                        String departmentArray = map.get("department").toString();
                        String department = departmentTrans(departmentArray) + ",";
                        user.setDepartment(department);
                        if (map.get("position") != null) {
                            user.setPosition(map.get("position").toString());
                        }
                        Object mobile = map.get("mobile");
                        if (mobile != null) {
                            user.setMobile(map.get("mobile").toString());
                        }
                        user.setGender(map.get("gender").toString());
                        Object email = map.get("email");
                        if (email != null) {
                            user.setEmail(map.get("email").toString());
                        }
                        if (map.get("telephone") != null) {
                            user.setTelephone(map.get("telephone").toString());
                        }
                        if (map.get("alias") != null) {
                            user.setAlias(map.get("alias").toString());
                        }
                        if (map.get("address") != null) {
                            user.setAddress(map.get("address").toString());
                        }
                        user.setStatus((Integer) map.get("status"));
                        user.setUsertype("1");
                        user.setIsSynchronize("1");
                        user.setStat(1);
                        log.info("=======新增第=======" + (i+1) + "个"+"手机号码" + mobile);
                        userDao.insert(user);
                        userService.saveDepartUser(department, user.getUserid());
                    }
                }
            }
        }
    }

    /**
     * 部门比较同步
     * 每日凌晨执行
     */
    //@Scheduled(cron = "0 0 0 1/1 * ?")
    //@Scheduled(cron = "0 8/10 * * * ?")
    public void departmentComparison() {
        String accessToken = restTemplateUtil.getaccessToken();
        //获取部门列表
        String deptUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + accessToken;
        Map resultMapDep = restTemplate.getForObject(deptUrl, Map.class);
        log.info(resultMapDep.toString());
        List departmentList = (List) resultMapDep.get("department");
        for (int a = 0; a < departmentList.size(); a++) {
            Map departmentMap = (Map) departmentList.get(a);
            Integer id = (Integer) departmentMap.get("id");
            DepartmentEntity departmentEntity = departmentDao.selById(id);
            if (departmentEntity == null) {
                //新增部门
                DepartmentEntity department = new DepartmentEntity();
                long depId = id.longValue();
                department.setId(depId);
                String name = departmentMap.get("name").toString();
                department.setName(name);
                Integer parentid = (Integer) departmentMap.get("parentid");
                long parentId = parentid.longValue();
                department.setParentid(parentId);
                department.setIsSynchronize("1");
                departmentDao.save(department);
            }
        }
    }

    /**
     * 标签同步
     * 每日凌晨执行
     */
    //@Scheduled(cron = "0 0 0 1/1 * ?")
    //@Scheduled(cron = "0 3/10 * * * ?")
    public void tagComparsion() {
        String accessToken = restTemplateUtil.getaccessToken();
        //获取标签列表
        String deptUrl = "https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token=" + accessToken;
        Map resultMap = restTemplate.getForObject(deptUrl, Map.class);
        log.info(resultMap.toString());
        List taglist = (List) resultMap.get("taglist");
        for (int i = 0; i < taglist.size(); i++) {
            Map map = (Map) taglist.get(i);
            Integer tagid = (Integer) map.get("tagid");
            TagEntity tagEntity = tagDao.selectById(tagid);
            if (tagEntity == null) {
                TagEntity tag = new TagEntity();
                Long tagId = tagid.longValue();
                tag.setIsSynchronize("1");
                tag.setTagid(tagId);
                tag.setTagname(map.get("tagname").toString());
                tagDao.saveTag(tag);
            }
        }
    }

    /**
     * 标签用户同步
     */
    //@Scheduled(cron = "0 50 0 1/1 * ?")
    //@Scheduled(cron = "0 5/10 * * * ?")
    public void taguserComparsion() {
        String accessToken = restTemplateUtil.getaccessToken();
        //获取标签列表
        String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token=" + accessToken;
        Map resultMap = restTemplate.getForObject(url, Map.class);
        log.info(resultMap.toString());
        List taglist = (List) resultMap.get("taglist");
        for (int i = 0; i < taglist.size(); i++) {
            Map map = (Map) taglist.get(i);
            Integer tagid = (Integer) map.get("tagid");
            //获取标签用户
            String tagUrl = "https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token=" + accessToken + "&tagid=" + tagid;
            Map result = restTemplate.getForObject(tagUrl, Map.class);
            log.info(result.toString());
            //标签用户
            List userlist = (List) result.get("userlist");
            for (int a = 0; a < userlist.size(); a++) {
                Map userMap = (Map) userlist.get(a);
                String userid = userMap.get("userid").toString();
                //根据标签id，用户id查询
                UserTagEntity userTagEntity = tagDao.selByUseridAandTagid(userid, tagid);
                if (userTagEntity == null) {
                    tagDao.saveTagUser(tagid.longValue(), userid);
                }
            }
        }
    }

    /**
     * 用户字段进行比对
     * 每日凌晨五十分执行
     */
    //@Scheduled(cron = "0 50 0 1/1 * ?")
    //@Scheduled(cron = "0 8/10 * * * ?")
    public void userFeildComparison() {
        String accessToken = restTemplateUtil.getaccessToken();
        //获取部门列表
        String deptUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + accessToken;
        Map resultMapDep = restTemplate.getForObject(deptUrl, Map.class);
        log.info(resultMapDep.toString());
        //定义set集合存放用户id
        Set<String> set = new HashSet<>();
        //获取所有部门
        List departmentList = (List) resultMapDep.get("department");
        for (int a = 0; a < departmentList.size(); a++) {
            Map departmentMap = (Map) departmentList.get(a);
            Integer id = (Integer) departmentMap.get("id");
            //部门人员信息
            String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + accessToken + "&department_id=" + id + "&fetch_child=" + 0;
            Map resultMap = restTemplate.getForObject(getUrl, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            if (code == 0) {
                List userList = (List) resultMap.get("userlist");
                //循环企业微信人员与平台作比较
                for (int i = 0; i < userList.size(); i++) {
                    Map userMap = (Map) userList.get(i);
                    String userid = userMap.get("userid").toString();
                    set.add(userid);
                    //根据userid获取成员信息
                    UserEntity userEntity = userDao.selectDetailById(userid);
                    if (userEntity != null) {
                        //字段对比
                        UserEntity user = new UserEntity();
                        if(!StringUtils.equals((String) userMap.get("name"),userEntity.getName())){
                            //姓名不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            continue;
                        }
                        if(!StringUtils.equals((String) userMap.get("alias"),userEntity.getAlias())){
                            //别名不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            continue;
                        }
                        /*if(!StringUtils.equals((String) userMap.get("mobile"),userEntity.getMobile())){
                            //手机号不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            continue;
                        }*/
                        String departmentArray = userMap.get("department").toString();
                        String department = departmentTrans(departmentArray);
                        boolean b = comparsionDepartment(department, userEntity.getDepartment());
                        if(b){
                            //部门不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            continue;
                        }
                        if(!StringUtils.equals((String) userMap.get("position"),userEntity.getPosition())){
                            //职位不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            continue;
                        }
                        if(!StringUtils.equals((String) userMap.get("gender"),userEntity.getGender())){
                            //性别不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            continue;
                        }
                        if(!StringUtils.equals((String) userMap.get("email"),userEntity.getEmail())){
                            //email不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            continue;
                        }
                        if(!StringUtils.equals((String) userMap.get("telephone"),userEntity.getTelephone())){
                            //座机不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            continue;
                        }
                        /*if(!StringUtils.equals((String) userMap.get("address"),userEntity.getAddress())){
                            //地址不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            break;
                        }*/
                        /*if(!StringUtils.equals((Integer) userMap.get("status")+"",userEntity.getStatus()+"")){
                            //状态不一致，设置数据异常
                            userEntity.setStat(2);
                            userDao.updateById(userEntity);
                            continue;
                        }*/
                    }
                }
            }
        }
        //将在我们数据库有的成员，在企业微信没有的成员设置为异常
            List<String> list = new ArrayList<>();
        log.info("==================" + set.size());
        list.addAll(set);
        userDao.batchUpdate(list);
    }

    /**
     * 部门转换
     * @param departmentArray
     * @return
     */
    public String departmentTrans(String departmentArray){
        String substring = departmentArray.substring(1, departmentArray.length() - 1);
        String[] split = substring.split(",");
        StringBuffer departments = new StringBuffer();
        for (int j = 0; j < split.length; j++) {
            departments.append(split[j].trim()).append(",");
        }
        String department = departments.substring(0, departments.length() - 1);
        return department;
    }

    public boolean comparsionDepartment(String wechatDepartment, String paltDepartment){
        String[] split = wechatDepartment.split(",");
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            if(!paltDepartment.contains(s)){
                return true;
            }
        }
        String[] split1 = paltDepartment.split(",");
        for (int i = 0; i < split1.length; i++) {
            String s = split1[i];
            if(!wechatDepartment.contains(s)){
                return true;
            }
        }
        return false;
    }
}
